package com.kongge.algorithm.demo;

import java.util.LinkedList;
import java.util.List;

/**
 * 输入一个字符串，打印出该字符串中字符的所有排列。
 * 例如abc,则打印出abc,acb,bac,bca,cab和cba.
 * @author kongge
 *
 */
public class RankStrings implements IAlgorithm {

	public void execute() {
		String str = "abc";
		List<String> resultList = getRankStrings(str);
		if (resultList != null) {
			for (int i = 0; i < resultList.size(); i++) {
				System.out.println(resultList.get(i).toString());
			}
		}
	}

	private List<String> getRankStrings(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		List<String> resultList = new LinkedList<String>();
		rankStrings(new StringBuilder(str), 0, resultList);
		return resultList;
	}
	
	private void rankStrings(StringBuilder sbStr, int beginIndex, List<String> resultList) {
		if (beginIndex == sbStr.length() - 1) {
			resultList.add(sbStr.toString());
			return;
		}
		for (int i = beginIndex; i < sbStr.length(); i++) {
			char temp = sbStr.charAt(beginIndex);
			sbStr.setCharAt(beginIndex, sbStr.charAt(i));
			sbStr.setCharAt(i, temp);
			
			rankStrings(sbStr, beginIndex + 1, resultList);
			
			temp = sbStr.charAt(beginIndex);
			sbStr.setCharAt(beginIndex, sbStr.charAt(i));
			sbStr.setCharAt(i, temp);
		}
	}
	
}
